//
//  AppDelegate.m
//  Project_B
//
//  Created by 黑黑 on 15/11/23.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "AppDelegate.h"
#import "SelfDefineTabBarViewController.h"
#import "WCG_M_mainViewController.h"
#import "WCG_Mine_ViewController.h"
#import "WCG_N_ViewController.h"
#import "WCG_O_ViewController.h"
#import "APService.h"
#import "AFNetworking.h"
#import "APIKey.h"
#import "AFNetworkReachabilityManager.h"
#import <iflyMSC/iflyMSC.h>

//  科大讯飞 key
static NSString *appid = @"565c065e";

@interface AppDelegate ()

@property (nonatomic, retain) UILabel *messageLabel;

@end

@implementation AppDelegate

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
    // Required
    [APService setupWithOption:launchOptions];

    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //  检测网络状态
    [self reachability];
    
#if 1   /* 科大讯飞 - 语音听写 */
    
    //  设置 SDK的 Log 等级, log 保存在下面设置的工作路径中
    [IFlySetting setLogFile:LVL_ALL];
    
    //  打开输出在 console 的 log 开关
    [IFlySetting showLogcat:YES];
    
    //  设置 sdk 的工作路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    NSLog(@"语音路径:%@", cachePath);
    [IFlySetting setLogFilePath:cachePath];
    
    //  创建语音配置 appid必须传入 仅执行一次即可
    NSString *initString = [NSString stringWithFormat:@"appid=%@", appid];
    
    //  所有服务启动之前 需要确保执行
    [IFlySpeechUtility createUtility:initString];
    
#endif
    
    // 第一个tabbar
    WCG_M_mainViewController *mVC = [[WCG_M_mainViewController alloc] init];
    UINavigationController *mna = [[UINavigationController alloc] initWithRootViewController:mVC];
    // 第二个tabbar
    WCG_N_ViewController *nVC = [[WCG_N_ViewController alloc] init];
    UINavigationController *nNa = [[UINavigationController alloc] initWithRootViewController:nVC];
    // 第三个tabbar
    WCG_O_ViewController *oVC = [[WCG_O_ViewController alloc] init];
    UINavigationController *oNa = [[UINavigationController alloc] initWithRootViewController:oVC];
    // 第四个tabbar
    WCG_Mine_ViewController *mineVC = [[WCG_Mine_ViewController alloc] init];
    UINavigationController *mineNa = [[UINavigationController alloc] initWithRootViewController:mineVC];
    SelfDefineTabBarViewController *selfDefineTabBar = [[SelfDefineTabBarViewController alloc] init];
    selfDefineTabBar.viewControllers = @[mna, oNa, nNa, mineNa];
    // UM
    [UMSocialData setAppKey:@"563c60e267e58e6ae1000680"];
    
    self.window.rootViewController = selfDefineTabBar;
    return YES;
}

#pragma mark - 网络监视器/判断网络类型
- (void)reachability {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager  sharedManager];
    //开启网络监视
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [self internetCheck:@"未知网络"];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [self internetCheck:@"无网络"];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [self internetCheck:@"Wifi网络"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [self internetCheck:@"蜂窝网络"];
                break;
            default:
                break;
        }
    }];
    // 监视结束
    [manager stopMonitoring];
}

#pragma mark - 网络状态提示
-(void)internetCheck:(NSString *)net
{
    NSString *netCondition = [NSString stringWithFormat:@"当前网络为%@",net];
    self.messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, kScreenWidth, 50)];
    self.messageLabel.text = [NSString stringWithFormat:@"%@", netCondition];
    self.messageLabel.textAlignment = NSTextAlignmentCenter;
    [self.window addSubview:self.messageLabel];
    
    [self.messageLabel setBackgroundColor:[UIColor lightGrayColor]];
    self.messageLabel.layer.cornerRadius = 5;
    self.messageLabel.layer.masksToBounds = YES;
    [self.messageLabel setTextColor:[UIColor whiteColor]];
    
    //  多线程弹出网络状态消息
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:2.0f animations:^{
            [self.messageLabel setFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        } completion:^(BOOL finished) {
            [self performSelector:@selector(hiddenMessageLabel) withObject:self.messageLabel afterDelay:1.0f];
        }];
    });
}

#pragma mark - 隐藏网络状态提示
- (void)hiddenMessageLabel {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:2.0f animations:^{
            [self.messageLabel setFrame:CGRectMake(0, -50, kScreenWidth, 50)];
        }];
    });
}

#pragma mark - 进入前后台设置消息信息
- (void)applicationWillEnterForeground:(UIApplication *)application {
    //进入前台取消应用消息图标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"%@", error);
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    [[IFlySpeechUtility getUtility] handleOpenURL:url];
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}

@end
